<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>编辑设备</span>
        <el-button type="primary" @click="goBack" plain>返回列表</el-button>
      </div>
    </template>
    
    <el-form 
      ref="formRef" 
      :model="form" 
      :rules="rules" 
      label-width="100px"
      label-position="top"
      style="max-width: 600px;"
      v-loading="loading"
    >
      <el-form-item label="区域" prop="areaId">
        <el-cascader
          v-model="form.areaId"
          :options="areaOptions"
          :props="areaProps"
          clearable
          placeholder="请选择区域"
          style="width: 100%;"
        />
      </el-form-item>
      
      <el-form-item label="设备型号" prop="model">
        <el-input 
          v-model="form.model" 
          placeholder="请输入设备型号" 
          clearable
        />
      </el-form-item>
      
      <el-form-item label="序列号" prop="serialNo">
        <el-input 
          v-model="form.serialNo" 
          placeholder="请输入设备出厂序列号" 
          clearable
          disabled
        />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
          <el-option label="在线" value="online" />
          <el-option label="离线" value="offline" />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">更新</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import DeviceAPI from '@/api/system/device.api';
import AreaAPI from '@/api/system/area.api';

const router = useRouter();
const route = useRoute();

const formRef = ref(null);
const loading = ref(false);
const form = reactive({
  id: null,
  areaId: null,
  model: '',
  serialNo: '',
  status: 'online',
});

const rules = reactive({
  areaId: [{ required: true, message: '请选择区域', trigger: 'change' }],
  model: [{ required: true, message: '请输入设备型号', trigger: 'blur' }],
  serialNo: [{ required: true, message: '请输入序列号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
});

const areaOptions = ref([]);
const areaProps = {
  label: 'name',
  value: 'id',
  children: 'children',
  checkStrictly: true,
};

// 加载区域数据
const loadAreaOptions = async () => {
  try {
    const res = await AreaAPI.getAll();
    areaOptions.value = res;
  } catch (error) {
    ElMessage.error('加载区域数据失败');
    console.error('加载区域数据失败:', error);
  }
};

// 加载设备详情
const loadDevice = async () => {
  loading.value = true;
  try {
    const id = route.params.id;
    if (!id) return;
    
    const res = await DeviceAPI.getById(id);
    Object.assign(form, res);
    
    // 设置区域选择器值
    if (res.areaId) {
      form.areaId = [res.areaId];
    }
  } catch (error) {
    ElMessage.error('加载设备信息失败');
    console.error('加载设备信息失败:', error);
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();
    const areaId = form.areaId ? form.areaId[form.areaId.length - 1] : null;
    
    await DeviceAPI.update({ 
      ...form, 
      areaId 
    });
    
    ElMessage.success('设备更新成功');
    goBack();
  } catch (error) {
    console.error('更新设备失败:', error);
    ElMessage.error(error.message || '更新设备失败');
  }
};

// 重置表单
const resetForm = () => {
  loadDevice();
};

// 返回列表
const goBack = () => {
  router.push({ name: 'deviceList' });
};

onMounted(() => {
  loadAreaOptions();
  loadDevice();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>